<?php

class Controller_Wallets extends Controller_Template
{

	public function action_index()
	{
        //get session id and get wallet.
        $user_id = Session::get('userid');
        //set pagnitor
        $config = array(
            'pagination_url' => 'http://localhost/fuelphp-ml/public/wallets/index',
            'total_items' => Model_Wallet::count(),
            'per_page' => 5,
            'uri_segment' => 3,
        );
        $pagination = Pagination::forge('mypagination', $config);
        $wallets = Model_Wallet::query()->limit($pagination->per_page)->offset($pagination->offset)->where('user_id',$user_id)->get();// returm orm/query if not include get(),include get return arrays == model
        $view = View::forge('wallets/index');
        //\Fuel\Core\Debug::dump($wallets);die();
        $view->wallets = $wallets;
        $this->template->js='wa_index.js';
        $this->template->title= 'Index Wallet page';
        $this->template->set('content', $view, false); //false will tell fuel not to convert the html tags to safe string
    }

	public function action_view($id = null)
	{
         $view = View::forge('wallets/view');
        $wallet = Model_Wallet::find($id);
//                $wallet=Model_Wallet::query()->related('users')->where('wallets.id', $id)->get();
        //\Fuel\Core\Debug::dump($wallet->users);die();
        $view->wallet = $wallet;
        $this->template->title = 'Wallets &raquo; View';
        $this->template->content = $view;
    }

	public function action_add()
    {
        $id = Session::get('userid');
        if (Input::method() == 'POST')
        {
            //check if have 5 wallet ,stop
            $count=Model_Wallet::query()->where('user_id', $id)->count();            
            if ($count == 5)
            {
                Session::set_flash('message', 'You have already had 5 wallets');
                Response::redirect('wallets/add');
            }
            //check money
            if (Input::post('current_money') < 0)
            {
                Session::set_flash('message', 'Invald Money');
                Response::redirect('wallets/add');
            }
            //save wallet
            $val = Validation::forge();
            $val = Model_Wallet::get_validation_add($val);
            if ($val->run())
            {   
                $wallet = Model_Wallet::forge($val->validated());
                $wallet->user_id=$id;
                $wallet->status=1;
                date_default_timezone_set('Asia/Saigon');
                $wallet->created_at = date('Y-m-d H:i:s');
                If($wallet->save())
                {  //if save succesfully,reset another wallet to not default!
                    $query = DB::query(" UPDATE tb_wallets
                                            SET status= 0
                                            WHERE id != '$wallet->id'")->execute();
                    Session::set_flash('message', 'The wallet '.$val->validated('name').' has been saved.');
                    Response::redirect('users/index');   
                }
                else
                {
                    Session::set_flash('message', 'There are some errors occur when saving data');            
                }
            }
            else
            {
               Session::set_flash('message',$val->show_errors());    
            }
        }
            //set input form before submit
            $view = View::forge('wallets/add');
            $this->template->title = 'add wallet';
            $this->template->set('content', $view, false); //false will tell fuel not to convert the html tags to safe string 
    }

    public function action_edit($id = null)
    {
        if (Input::method() == 'POST')
        {
            //tạo validation va xet va tao model va luu vao co so du lieu
            $val = Validation::forge();
            $val = Model_Wallet::get_validation_edit($val); //trong nay van thieu dk kiem tra trung email hay username vs ng khac
            if ($val->run())
            {   
                $wallet = Model_Wallet::find($id);
                $wallet->name=Input::post('name');
                $wallet->current_money=Input::post('current_money');       
                $wallet->save();
                Session::set_flash('message', 'The informations has been changed.');
                Response::redirect('wallets/index');
            }
            else
            {
                Session::set_flash('message', $val->show_errors());
            }
        }
        $view = View::forge('wallets/edit');
        $wallet = Model_Wallet::find($id);
        $view->wallet = $wallet;
        $this->template->title = 'edit wallet';
        $this->template->set('content', $view, false);
    }

    public function action_delete($id=null)
	{
		$wallet = Model_Wallet::find($id);
                $wallet->delete();
                Response::redirect('wallets/index');
                
	}
    
    public function action_setdefault()
    {

        if (Input::is_ajax())
        {
            //get $_Post['id'] ;         
            $id = Input::post('id');
            //reset
            $query = DB::query(" UPDATE tb_wallets SET status= 0")->execute();
            $wallet = Model_Wallet::find($id);
            $wallet->status = 1;
            if ($wallet->save())
            {
                Session::set_flash('message', 'Wallets has been changed!');
                echo "ok";
            } else
            {
                Session::set_flash('message', 'Errors!');
            }
        }
    }

}
